const base_url = "http://124.93.196.45:10001"

// 创建拦截器
const interceptor = {
	invoke(option) {
		if(!option.url.startsWith("http"))
		{
			option.url=base_url+option.url
			console.log(option.url)
		}
		// 添加请求头
		// option.header = {}
		// 获取token
		let token = uni.getStorageSync("token")
		// console.log("token："+token)
		// 如果token不为空，将token添加到请求头中
		if(!option.header)
		{
			option.header={}
		}
		if(token)
		{
			option.header.Authorization=token
		}
	}
}



// 为request请求添加拦截器
uni.addInterceptor("request", interceptor)
uni.addInterceptor('uploadFile', interceptor)
const reqeust = function(url, data, method = "GET" ) {
	console.log("url:" + url)
	uni.showLoading({
		title: "加载中..."
	})
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data: data || {},
			method,
			success: (res) => {
				//根据返回的状态码（参考接口手册）进行不同操作
				switch (res.data.code) {
					//正常
					case 200:
						resolve(res.data)
						break;
						// 未授权(在访问需要token的页面时候,未携带token)
					case 401:
						uni.removeStorageSync("token")
						// 关闭所有页面返回到登录页
						uni.reLaunch({
							url: "/pages/index/index"
						});
						break;
						// 其他情况,错误
					default:
						// 错误提示
						uni.showToast({
							icon: 'error',
							title: res.data.message
						});
						reject(res);
						break;
				}
			},
			fail: (err) => {
				reject(err)
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	})
}

uni.$base_url = base_url
// uni.$request=request
uni.$get = function(url, data) {
	return reqeust(url, data, "GET")
}
uni.$post = function(url, data) {
	console.log(data)
	return reqeust(url, data, "POST")
}
uni.$put = function(url, data) {
	return request(url, data, "PUT")
}
uni.$delete = function(url, data) {
	return reqeust(url, data, "DELETE")
}